<template>
  <div>
    <h2 style="text-align: center">采购入库</h2>
    <table width="100%">
      <tr><td>供应商<input v-model="buyObj.supplier"></td>
        <td>采购员：{{loginUser.realName}}</td></tr>
      <tr style="height: 20px;font-size: 12px;color: red"><td>{{errorInfo}}</td></tr>
    </table>
    <el-table :data="buyList" border stripe style="width: 100%">
      <el-table-column prop="product.name" label="商品名称"  />
      <el-table-column label="采购价" >
        <template #default="scope">
          <el-input  type="primary" size="small" v-model="scope.row.price" @blur="updateInfo(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="采购数量" >
        <template #default="scope">
          <el-input  type="primary" size="small" v-model="scope.row.number" @blur="updateInfo(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="220">
        <template #default="scope">
          <el-button  type="primary" size="small" @click="removeProduct(scope.row)">移除商品</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 20px;text-align: center">
      <el-button  type="primary" size="small" @click="showAdd = true">添加商品</el-button>
      <el-button  type="success" size="small" @click="addRespository()">入库</el-button>
    </div>

    <!--添加采购商品对话框-->
    <el-dialog
        v-model="showAdd"
        title="添加采购商品"
        width="80%"
    >
      <el-row>
        <el-col :span="2"></el-col>
        <el-col :span="18">
          <el-row>
            <el-col :span="14">
              <el-form
                  ref="ruleFormRef"
                  :model="buyProductObj"
                  :rules="rules"
                  label-width="120px"
                  class="demo-ruleForm"
                  status-icon
              >
                <el-form-item label="商品编号" prop="id">
                  <el-input v-model="buyProductObj.id" @blur="findProduct()"/>
                </el-form-item>

                <el-form-item label="商品名" prop="name">
                  <el-input :disabled="isFind"  v-model="buyProductObj.name"/>
                </el-form-item>

                <el-form-item label="类别" prop="type">
                  <el-select v-model="buyProductObj.type" :disabled="isFind" class="m-2" placeholder="请选择类别" size="large">
                    <el-option  label="电脑产品" value="电脑产品"/>
                    <el-option  label="安防产品" value="安防产品"/>
                    <el-option  label="打印扫描设备" value="打印扫描设备"/>
                    <el-option  label="办公耗材" value="办公耗材"/>
                  </el-select>
                </el-form-item>

                <el-form-item label="采购数量" prop="buyNum">
                  <el-input   v-model="buyProductObj.buyNum"/>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="10">
              <img :src="'/project/productImg/'+buyProductObj.picture" id="pimg" width="200" height="150"><br>
              <input type="file" :disabled="isFind"  id="filetxt" @change="changeFace()">
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="2"></el-col>
      </el-row>

      <template #footer>
      <span class="dialog-footer">
        <el-button type="success" @click="addShop()">添加</el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import axios from "axios";
import {ElMessageBox} from "element-plus";
export default {
  data() {
    return {
      errorInfo:"", //错误信息
      buyObj:{}, //采购信息对象
      buyProductObj:{}, //购买商品对象
      loginUser:{}, //登陆用户
      showAdd:false, //是否显示添加商品弹出框
      buyList:[], //采购车集合
      isFind:false, //添加进采购车的商品，在库存中是否存在
      rules: { //验证正则表达式
        id: [{required: true,message:'请输入编号',trigger: 'blur' },
          {pattern:/^\d+$/,
            message: '商品编号为数字', trigger: 'blur' }],
        name: [{required: true,message:'请输入商品名',trigger: 'blur' },
          {pattern:/^[a-zA-Z0-9\u4e00-\u9fa5]{2,}$/,
            message: '商品名为2位以上的字母、数字、汉字', trigger: 'blur' }],
        type: [
          {required: true,message:'请选择类别',trigger: 'change' }],
        buyNum: [
          {required: true,message:'请输入采购数量',trigger: 'blur' },
          {pattern:/^\d+$/,
            message: '采购数量必须为数字', trigger: 'blur' }]
      }
    }
  },
  methods:{
    findProduct(){ //按ID查询商品
      axios.get("/project/product/findById",{
        params:{
          id:this.buyProductObj.id
        }
      }).then(resp =>{
        var pobj = resp.data;
        if(pobj != ""){//库存中有该商品
          this.buyProductObj = pobj;
          this.isFind = true;
        }
        else{//库存不存在该商品
          this.buyProductObj.name = null;
          this.buyProductObj.type = null;
          this.buyProductObj.buyNum = null;
          this.buyProductObj.picture = null;
          this.isFind = false;
        }
      })
    },
    async addShop(){//添加进采购车
      var isPass;
      await this.$refs.ruleFormRef.validate((valid) => {
        if(valid){//valid为true表示验证通过
          isPass = true;
        }
        else{//valid为false表示验证失败
          isPass = false;
        }
      });
      if(isPass == false){return;}

      //将购买对象的操作赋值
      this.buyProductObj.option = this.isFind == true ? "update" : "add";
      //封装表单数据
      var formObj = new FormData();
      formObj.append("id",this.buyProductObj.id);
      formObj.append("option",this.buyProductObj.option);
      formObj.append("name",this.buyProductObj.name);
      formObj.append("type",this.buyProductObj.type);
      formObj.append("buyNum",this.buyProductObj.buyNum);
      formObj.append("productPic",document.getElementById("filetxt").files[0]);

      let config = {
        headers: {'Content-Type': 'multipart/form-data' }
      }
      axios.post("/project/buyShop/buy",formObj,config).then(resp =>{
          if(resp.data == "ok"){
            this.getBuyList();
            this.showAdd = false;
          }
      });

    },
    getBuyList(){//得到采购车信息
      axios.get("/project/buyShop/getBuyList").then(resp =>{
        this.buyList = resp.data;
      });
    },
    removeProduct(shopObj){//移除采购车商品
      axios.get("/project/buyShop/removeBuy",{
        params:{
          productId:shopObj.product.id
        }
      }).then(resp =>{
        if(resp.data == "ok"){
          this.getBuyList();
        }
      })
    },
    updateInfo(shopObj){//修改采购信息
        axios.get("/project/buyShop/updateBuyInfo",{
          params:{
            productId:shopObj.product.id,
            buyPrice:shopObj.price,
            buyNum:shopObj.number
          }
        }).then(resp =>{
          if(resp.data == "ok"){
            this.getBuyList();
          }
        })
    },
    addRespository(){//入库
      var einfo = "";
      if(this.buyObj.supplier==null || this.buyObj.supplier.trim().length == 0){
        einfo += "供应商必须填写";
      }
      if(this.buyList.length == 0){
        einfo += " 请添加采购商品";
      }
      if(einfo.length != 0){
        this.errorInfo = einfo;
        return;
      }

      axios.get("/project/procurement/addRespository",{
        params:this.buyObj
      }).then(resp =>{
        if(resp.data == "ok"){
          this.getBuyList();
          this.buyObj = {};
        }
      })

    },
    changeFace(){//图片预览
      var reader = new FileReader();//定义文件读取流对象
      reader.readAsDataURL(document.getElementById('filetxt').files[0]);
      reader.onload = (ev) =>{
        document.getElementById("pimg").src = ev.target.result;
      }
    }
  },
  created() {
    this.getBuyList();
    var loginInfo = sessionStorage.getItem("loginUser");
    if(loginInfo != null) {
      this.loginUser = JSON.parse(loginInfo);
    }
  }
}
</script>

<style scoped>

</style>